<template>
  <!--  负责人筛选-->
  <div class="person-filter" v-loading="isLoading">
    <div class="person-tabs">
      <div
        class="person-tabs__item"
        :class="{ 'person-tabs__item--active': item.filterId === activeTab }"
        :key="item.filterId"
        v-for="item in tabs"
        @click="handelClickTab(item)"
      >
        <div class="item-label">{{ item.title }}</div>
      </div>
    </div>
    <!--  按负责人 start  -->
    <div class="person-search" v-if="activeTab === 'principal_id'">
      <div class="person-search__input">
        <el-input placeholder="请输入关键词" v-model="keywords" @input="handelSearch" />
        <svg-icon icon-class="search-icon" size="24" />
      </div>
      <div class="person-search__list" v-if="portraitList.length">
        <el-checkbox-group v-model="filterListData[0].value">
          <el-checkbox :value="item.id" v-for="item in portraitList" :key="item.id">
            <span>{{ item.labelName }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <el-empty v-else :image-size="60" />
    </div>
    <!--  按负责人 end  -->

    <!--   按角色 start -->
    <div class="role-filter" v-if="activeTab === 'principal_role_id'">
      <div class="role-filter__list" v-if="roleList.length">
        <el-checkbox-group v-model="filterListData[0].value">
          <el-checkbox :value="item.value" v-for="item in roleList" :key="item.value">
            <span>{{ item.label }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <el-empty v-else :image-size="60" />
    </div>
    <!--  按角色 end  -->

    <!--   按部门 start -->
    <div class="dept-filter" v-if="activeTab === 'principal_dept_id'">
      <el-tree
        v-if="deptDataTree.length"
        ref="deptTree"
        :data="deptDataTree"
        default-expand-all
        show-checkbox
        node-key="id"
        :props="defaultProps"
      />
      <el-empty v-else :image-size="60" />
    </div>
    <!--  按部门 end  -->

    <div class="person-filter__buttons">
      <el-button type="primary" class="buttons-cancel" link size="default" @click="handelReset">重置</el-button>
      <el-button type="primary" class="buttons-confirm" size="default" @click="handelConfirm">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick, watch } from "vue";
import { cloneDeep } from "lodash";
import { getRole } from "@/apis/system";
import { departmentTree } from "@/apis/user";
import { getAllListByType } from "@/apis/system";
import { tabs } from "./config";

const { proxy } = getCurrentInstance();
const props = defineProps({
  filterList: {
    type: Array,
    default: () => [{ ...tabs[0] }]
  }
});
const emit = defineEmits(["handelFilterData"]);

const isLoading = ref(false);
/**
 * 默认按负责人
 * type=principal 负责人,type=task 任务,type=stage 阶段
 */
const keywords = ref("");
const portraitList = ref([]);
let clonePortraitList = [];
const getPortraitList = async () => {
  try {
    isLoading.value = true;
    const { data } = await getAllListByType({ type: "principal" });
    portraitList.value = data ?? [];
    clonePortraitList = cloneDeep(data ?? []);
    isLoading.value = false;
  } catch (err) {
    console.log(err);
    isLoading.value = false;
  }
};
const handelSearch = () => {
  portraitList.value = clonePortraitList.filter(item => item.labelName.includes(keywords.value));
};

/**
 * 角色
 */
const roleList = ref([]);
const getRoleList = async () => {
  try {
    isLoading.value = true;
    const { data } = await getRole();
    roleList.value =
      data?.map(item => ({
        label: item.roleName,
        value: item.roleId
      })) || [];
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    console.log(err);
  }
};

/**
 * 部门
 */
const defaultProps = {
  children: "children",
  label: "deptName"
};
const deptDataTree = ref([]);
const fixTreeData = data => {
  return data.map(item => {
    if (!item.children || !Array.isArray(item.children)) {
      item.children = [];
    }
    item.children = fixTreeData(item.children);
    return {
      id: item.id,
      deptName: item.deptName,
      children: [...item.children]
    };
  });
};
const getDeptList = async () => {
  try {
    isLoading.value = true;
    const { data } = await departmentTree();
    deptDataTree.value = fixTreeData(data ?? []);
    await nextTick();
    proxy.$refs.deptTree.setCheckedKeys([]);
    filterListData.value[0]?.value?.forEach(i => {
      let node = proxy.$refs.deptTree.getNode(i);
      if (node.isLeaf) {
        proxy.$refs.deptTree.setChecked(node, true);
      }
    });
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    console.log(err);
  }
};

/**
 * 切换
 */
const requestData = new Map([
  ["principal_id", getPortraitList],
  ["principal_role_id", getRoleList],
  ["principal_dept_id", getDeptList]
]);
const activeTab = ref("principal_id");
const handelClickTab = item => {
  if (activeTab.value === item.filterId) return;
  activeTab.value = item.filterId;
  filterListData.value = [{ ...item }];
  requestData.get(item.filterId)();
};

const filterListData = ref([]);
watch(
  () => props.filterList,
  newVal => {
    filterListData.value = cloneDeep(newVal?.length ? newVal : []);
    if (filterListData.value.length) {
      activeTab.value = filterListData.value[0].filterId;
    }
  },
  { deep: true, immediate: true }
);
const handelReset = () => {
  if (filterListData.value[0].filterId === "principal_id") {
    keywords.value = "";
  }
  filterListData.value[0] = cloneDeep(tabs[0]);
  emit("handelFilterData", filterListData.value);
};
const handelConfirm = async () => {
  if (filterListData.value[0].filterId === "principal_dept_id") {
    await nextTick();
    const treeInstance = proxy.$refs.deptTree;
    const checkedKeys = treeInstance.getCheckedKeys();
    const halfCheckedKeys = treeInstance.getHalfCheckedKeys();
    filterListData.value[0].value = [...checkedKeys, ...halfCheckedKeys];
  }
  emit("handelFilterData", filterListData.value);
};

requestData.get(activeTab.value)();
</script>

<style scoped lang="scss">
@import "personFilter";
</style>
